package com.rongshu.sendmessage.activity;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.alibaba.fastjson.JSONObject;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.rongshu.sendmessage.R;
import com.rongshu.sendmessage.base.BaseActivity;
import com.rongshu.sendmessage.base.MyApplication;
import com.rongshu.sendmessage.bean.HuoYunBean;
import com.rongshu.sendmessage.util.ClientPublicParamUtil;
import com.rongshu.sendmessage.util.DialogUtil;
import com.rongshu.sendmessage.util.NetworkState;
import com.rongshu.sendmessage.util.PermissionUtils;
import com.rongshu.sendmessage.util.ProgressDialog;
import com.rongshu.sendmessage.util.StringUtils;
import com.rongshu.sendmessage.util.ToastUtils;
import com.rongshu.sendmessage.util.event.EventBuilder;
import com.rongshu.sendmessage.util.event.EventManager;
import com.rongshu.sendmessage.util.event.ShowGuidEvent;
import com.rongshu.sendmessage.util.httpUtil.HYContent;
import com.rongshu.sendmessage.util.httpUtil.IModel;
import com.rongshu.sendmessage.util.wx.WChartUtil;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.Subscribe;
import org.json.JSONException;

import com.gyf.immersionbar.ImmersionBar;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

//import cn.jpush.android.api.JPushInterface;


public class HYLoginActivity extends BaseActivity {
    private EditText et_user_name;
    private EditText et_user_psw;
    private Button btn_login;
    private TextView tv_regist;
    private ProgressDialog dialog;
    private PermissionUtils permissionUtils;
    private IWXAPI msgAPI;
    private View tv_forwordPassword;
//    private TTAdNative mTTAdNative;
    private Handler mHandler = new Handler(Looper.getMainLooper());
    private boolean isChecked=true;
    private CheckBox cb_show_pwd;
    private Intent mIntent;
//    private ViewSkeletonScreen skeletonScreen;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ImmersionBar.with(this)
                .statusBarColor(R.color.login_color)
                .statusBarDarkFont(true)
                .init();
//        msgAPI = WXAPIFactory.createWXAPI(HYLoginActivity.this, Constant_Third_ID.weixin_app_id);
        setContentView(R.layout.activity_hylogin);
        mContext = this;
        initView();
        String loginname = MyApplication.mSettings.getString(HYContent.LOGIN_NAME, "");
        String password = MyApplication.mSettings.getString(HYContent.Password, "");
//        if (HYContent.ISDEBUG) {
//            et_user_name.setText(loginname);
//            et_user_psw.setText(password);
//        }
        initBusEvents();
        boolean isxieyi=MyApplication.mSettings.getBoolean(MyApplication.IS_TONGYI_XIEYI,false);
        if (!isxieyi){

//            JPushInterface.stopPush(this);
            showYinSiDialog();
        }
    }
    private void showYinSiDialog() {
        DialogUtil.showYinSiDialog(mContext,new DialogUtil.OnDialogEvent<Integer>(){
            @Override
            public void onPositiveButtonClick(Integer i) {
                super.onPositiveButtonClick(i);
                switch (i){
                    case 0:
                        mIntent=new Intent(mContext, WebYinSiActivity.class );
                        mIntent.putExtra("souce","fuwu");
                        startActivity(mIntent);
                        break;
                    case 1:
                        mIntent=new Intent(mContext, WebYinSiActivity.class );
                        mIntent.putExtra("souce","yinsi");//https://www.jianshu.com/p/433de087db7e"
                        startActivity(mIntent);
                        break;
                    case 2:
                        finish();
                        MyApplication.instance.onTerminate();
                        break;
                }

            }
        });

    }
    private void initBusEvents() {
        EventManager.init(() -> new EventBuilder());
        EventManager.register(this);
    }

    @Subscribe
    public void event(ShowGuidEvent pEvent) {
        if(pEvent.getIndex()==1000){
            WChartUtil.getWChartToken(pEvent.getCode(), mContext, new WChartUtil.IWchartLogin() {
                @Override
                public void onSuccess() {
                    String wcharState=MyApplication.mSettings.getString(HYContent.WCHAT_LOGIN_STATE,"");
                    if(StringUtils.isEmpty(wcharState)||"activity".equals(wcharState)){
                        finish();
                    }
                }
                @Override
                public void onError() {
                }
            });
            EventManager.unregister(this);
        }
    }

    private void initView() {
        et_user_name = findViewById(R.id.et_user_name);
        et_user_name.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s!=null&&s.toString().length()>0){
                    String teamStr=s.toString();
                    if (teamStr.length()>19){
                        et_user_name.setText(teamStr.substring(0,19));
                        et_user_name.setSelection(19);
                        ToastUtils.show(mContext,"账号长度最多19位");
                    }
                }
            }
        });
        TextView title = findViewById(R.id.title);
        title.setText("登陆");
        et_user_psw = findViewById(R.id.et_user_psw);
        et_user_psw.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s!=null&&s.toString().length()>0){
                    String teamStr=s.toString();
                    if (teamStr.length()>29){
                        et_user_psw.setText(teamStr.substring(0,29));
                        et_user_psw.setSelection(29);
                        ToastUtils.show(mContext,"密码长度最多29位");
                    }
                }
            }
        });
        btn_login = findViewById(R.id.btn_login);
        tv_forwordPassword = findViewById(R.id.tv_forwordPassword);
        tv_regist = findViewById(R.id.tv_regist);
        CheckBox cb_xiexi = findViewById(R.id.cb_xiexi);
        String source = getIntent().getStringExtra("source");
        LinearLayout titleLayLeft = findViewById(R.id.titleLayLeft);
        if("user".equals(source)){
            titleLayLeft.setVisibility(View.VISIBLE);
            titleLayLeft.setOnClickListener(view->{
                finish();
            });
        }else{
            titleLayLeft.setVisibility(View.GONE);
        }
        isChecked=cb_xiexi.isChecked();
        cb_xiexi.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
                HYLoginActivity.this.isChecked=isChecked;
            }
        });
        View re_login_main = findViewById(R.id.re_login_main);
        cb_show_pwd = (CheckBox) findViewById(R.id.cb_show_pwd);
        cb_show_pwd.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    //如果选中，显示密码
                    et_user_psw.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                } else {
                    //否则隐藏密码
                    et_user_psw.setTransformationMethod(PasswordTransformationMethod.getInstance());
                }
                int length = et_user_psw.getText().length();
                et_user_psw.setSelection(length);
            }
        });
    }

    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.btn_login) {
            if(!isChecked){
                ToastUtils.show(mContext,"请先同意协议后登录哦");
                return;
            }
            login();
        } else if (id == R.id.btn_xianfeng) {
            String str = sHA1(mContext);
            ToastUtils.show(mContext, str);
//            Intent intent = new Intent(mContext, XFMainHomeActivity.class);
//            startActivity(intent);
        } else if (id == R.id.tv_forwordPassword) {
            Intent intent = new Intent(mContext, ForgetPasswordActivity.class);
            intent.putExtra("source", "login");
            startActivityForResult(intent, 1000);
//            Intent intent = new Intent(mContext, DrawLiuActivity.class);
//            startActivity(intent);
        } else if (id == R.id.tv_regist) {
            Intent intent = new Intent(mContext, HYRegistActivity.class);
            intent.putExtra("source", "login");
            startActivityForResult(intent, 1000);
        }else if (id == R.id.tv_xieyi) {
            mIntent=new Intent(mContext, WebYinSiActivity.class );
            mIntent.putExtra("souce","fuwu");
            startActivity(mIntent);
        }else if (id == R.id.tv_xieyi1) {
            mIntent=new Intent(mContext, WebYinSiActivity.class );
            mIntent.putExtra("souce","yinsi");//https://www.jianshu.com/p/433de087db7e"
            startActivity(mIntent);

        } else if (id == R.id.llWXLogin) {
            Log.i("111", "+++" + "点击了吗");
            if (NetworkState.isNetworkConnected(HYLoginActivity.this)) {
//                MyApplication.editor.putString(HYContent.WCHAT_LOGIN_STATE,"activity");
//                MyApplication.editor.commit();
//                SendAuth.Req req = new SendAuth.Req();
//                req.scope = "snsapi_userinfo";//
////                req.scope = "snsapi_login";//提示 scope参数错误，或者没有scope权限
//                req.state = "wechat_sdk_微信登录";
//                msgAPI.sendReq(req);
                Toast.makeText(HYLoginActivity.this, "开发中...", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(HYLoginActivity.this, "网络未连接，请检查网络设置", Toast.LENGTH_SHORT).show();
            }
        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1000 && resultCode == 1000) {
            finish();
            Intent intent = new Intent(mContext, MainActivity.class);
            startActivity(intent);
        }
    }

    //TODO 微信登陆结束了

    private void login() {
        if (StringUtils.isBlank(et_user_name.getText().toString()) || et_user_name.getText().toString().length() < 8) {
            ToastUtils.show(mContext, "请输入你的账号必须大于8位");
            return;
        }
        if (StringUtils.isBlank(et_user_psw.getText().toString()) || et_user_psw.getText().toString().length() < 6) {
            ToastUtils.show(mContext, "请输入大于等于6位的密码");
            return;
        }
        showProgress();
        Map<String, String> param = new HashMap<String, String>();
        param.put("username", et_user_name.getText().toString());//18332352851
        param.put("password", et_user_psw.getText().toString());
        param.put("clientPublicParam", ClientPublicParamUtil.getPublicParams(mContext));
        OkGo.<String>post(new HYContent().LOGIN_URL).params(param).execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {//Driver司机，VehicleOwner车主
                IModel.AjaxResult jr = new IModel.AjaxResult(response.body(),false);
                Log.d("user", response.body());
                final int code = jr.getCode();
                HuoYunBean huoYunBean = null;
                if (code > 0) {
                    huoYunBean = JSONObject.toJavaObject(jr.getData(), HuoYunBean.class);
                    if (huoYunBean != null) {
                        huoYunBean.setLoginName(et_user_name.getText().toString());
                        huoYunBean.setPassword(et_user_psw.getText().toString());
                        HYContent.saveUser(huoYunBean);
                        hideProgress();

                        try {
//                            org.json.JSONObject jsonObject = new org.json.JSONObject(huoYunBean.getUserIdentitys());

//                            MyApplication.editor.putString(HYContent.USET_TYPE, typeUser);
                            Intent intent = new Intent(mContext, MainActivity.class);
                            intent.putExtra("message","login");
                            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivity(intent);
                        } catch (Exception e) {
                            MyApplication.editor.putString(HYContent.USET_TYPE, "");

                            e.printStackTrace();
                            Intent intent = new Intent(mContext, MainActivity.class);
                            startActivity(intent);
                        }

                        MyApplication.editor.commit();
                        finish();
                    } else {
                        ToastUtils.show(mContext, "操作失败");
                        hideProgress();
                    }
                } else {
                    ToastUtils.show(mContext, jr.getMsg());
                    hideProgress();
                }
            }

            @Override
            public void onError(Response<String> response) {
                ToastUtils.show(mContext, "操作失败");
                hideProgress();
                String body = response.body();


            }
        });

    }


    public void showProgress() {
        dialog = ProgressDialog.createDialog(this);
        dialog.show();
    }

    public void hideProgress() {
        if (dialog != null) {
            dialog.dismiss();
        }
    }

    private String sHA1(Context context) {
        try {
            PackageInfo info = context.getPackageManager().getPackageInfo(context.getPackageName(), PackageManager.GET_SIGNATURES);
            byte[] cert = info.signatures[0].toByteArray();
            MessageDigest md = MessageDigest.getInstance("SHA1");
            byte[] publicKey = md.digest(cert);
            StringBuffer hexString = new StringBuffer();
            for (int i = 0; i < publicKey.length; i++) {
                String appendString = Integer.toHexString(0xFF & publicKey[i]).toUpperCase(Locale.US);
                if (appendString.length() == 1)
                    hexString.append("0");
                hexString.append(appendString);
                hexString.append(":");
            }
            String result = hexString.toString();
            return result.substring(0, result.length() - 1);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }
    protected void onDestroy() {
        super.onDestroy();
        mHandler.removeCallbacksAndMessages(null);
        EventManager.unregister(this);
    }
}
